using B.S.XZYData.Api.Wrter.Application.Command.ZSH;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.ZSH
{
	/// <summary>
	/// 导入不良品项（NPOI）
	/// 模板列：DefectiveCode(可空)、DefectiveName、AttachmentPath(可空)、ImagePath(可空)
	/// </summary>
	public class ImportDefectiveHandler : IRequestHandler<ImportDefectiveCommand, ApiResult<int>>
	{
		private readonly IBaseRepository<Defective> _repo;

		public ImportDefectiveHandler(IBaseRepository<Defective> repo)
		{
			_repo = repo;
		}

		public async Task<ApiResult<int>> Handle(ImportDefectiveCommand request, CancellationToken cancellationToken)
		{
			var res = new ApiResult<int>();
			if (request.File == null || request.File.Length == 0)
			{
				res.Code = ApiEnum.Fail;
				res.Msg = "请选择要导入的文件";
				return res;
			}

			int success = 0;
			using var stream = request.File.OpenReadStream();
			IWorkbook workbook = new XSSFWorkbook(stream);
			var sheet = workbook.GetSheetAt(0);
			for (int i = 1; i <= sheet.LastRowNum; i++) // 从第2行开始
			{
				var row = sheet.GetRow(i);
				if (row == null) continue;

				string code = row.GetCell(0)?.ToString()?.Trim();
				string name = row.GetCell(1)?.ToString()?.Trim();
				string attachment = row.GetCell(2)?.ToString()?.Trim();
				string image = row.GetCell(3)?.ToString()?.Trim();

				if (string.IsNullOrWhiteSpace(name)) continue; // 名称必填

				// 编号为空自动生成，或校验唯一
				if (string.IsNullOrEmpty(code))
				{
					string GenCode() => $"BL{DateTime.Now:yyyyMMddHHmmssfff}{new Random().Next(10,99)}";
					code = GenCode();
					int guard = 0;
					while (_repo.GetAll().Any(x => !x.IsDeleted && x.DefectiveCode == code) && guard < 5)
					{
						await Task.Delay(2, cancellationToken);
						code = GenCode();
						guard++;
					}
				}
				else if (_repo.GetAll().Any(x => !x.IsDeleted && x.DefectiveCode == code))
				{
					// 已存在则跳过或可选择更新，这里选择跳过
					continue;
				}
				if (_repo.GetAll().Any(x => !x.IsDeleted && x.DefectiveName == name))
				{
					// 名称重复跳过
					continue;
				}

				var entity = new Defective
				{
					DefectiveCode = code,
					DefectiveName = name,
					AttachmentPath = attachment,
					ImagePath = image,
					CreateTime = DateTime.Now,
					CreatorId = request.CreatorId,
					IsDeleted = false
				};

				success += await _repo.CreateAsync(entity);
			}

			res.Code = ApiEnum.Success;
			res.Msg = $"导入完成，成功 {success} 条";
			res.Data = success;
			return res;
		}
	}
}


